<?php
/**
 * 微信图文管理
 * User: Administrator
 * Date: 2019/11/27 0027
 * Time: 13:32
 */

namespace app\admin\controller;

use app\admin\traits\controller\WxNews;
use service\DataService;
use service\LogService;
use service\WechatService;
use think\Db;
use think\response\View;

class WechatNews extends BasicAdmin{

    use WxNews;

    /**
     * 设置默认操作表
     * @var string
     */
    public $table = 'WechatNews';

    /**
     * 图文列表
     */
    public function index()
    {
        if($this->request->isPost()) {
            $param = $this->request->param();
            $db = Db::name($this->table)->where('delete_at', '0')->order('id desc');
            return parent::_list($db,$param);
        }
        $this->title = '微信管理 > 图文列表';
        return $this->fetch('wechat/news/index', ['title' => $this->title]);
    }

    /**
     * 图文选择器
     * @return string
     */
    public function select()
    {
        return $this->index();
    }

    /**
     * 媒体资源显示
     * @return array
     */
    public function image()
    {
        $_GET['rows'] = 18;
        $this->assign('field', $this->request->get('field', 'local_url'));
        return $this->_list(Db::name('WechatNewsMedia')->where('type', 'image'));
    }

    /**
     * 添加图文
     * @return View
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $data = $this->request->param();
            if (($ids = $this->_apply_news_article($data['data'])) && !empty($ids)) {
                $post = ['article_id' => $ids, 'create_by' => session('user.id')];
                if (DataService::save($this->table, $post, 'id') !== false) {
                    $this->success('图文添加成功！', '');
                }
            }
            $this->error('图文添加失败，请稍候再试！');
        }
        return $this->fetch('wechat/news/form',['iframe'=>$this->request->get('iframe')]);
    }

    /**
     * 编辑图文
     * @return View
     */
    public function edit()
    {
        $id = $this->request->get('id', '');
        if ($this->request->isGet()) {
            empty($id) && $this->error('参数错误，请稍候再试！');
        }
        if($this->request->isPost()){
            $data = $this->request->post();
            $ids = $this->_apply_news_article($data['data']);
            if (!empty($ids)) {
                $post = ['id' => $id, 'article_id' => $ids, 'create_by' => session('user.id')];
                if (false !== DataService::save('wechat_news', $post, 'id')) {
                    $this->success('图文更新成功!', '');
                }
            }
            $this->error('图文更新失败，请稍候再试！');
        }
        $data = [
            'vo' => WechatService::getNewsById($id),
            'iframe' => $this->request->get('iframe')
        ];
        return $this->fetch('wechat/news/form',$data);
    }



    /**
     * 删除图文
     */
    public function del()
    {
        if (DataService::update($this->table)) {
            $this->success("图文删除成功!", '');
        }
        $this->error("图文删除失败, 请稍候再试!");
    }

    /**
     * 推荐图文
     * @return array
     */
    public function push()
    {
        # 获取将要推送的粉丝列表
        switch (strtolower($this->request->get('action', ''))) {
            case 'getuser':
                if ('' === ($params = $this->request->post('group', ''))) {
                    return ['code' => 'SUCCESS', 'data' => []];
                }
                list($ids, $db) = [explode(',', $params), Db::name('WechatFans')];
                !in_array('0', $ids) && $db->where("concat(',',tagid_list,',') REGEXP '," . join(',|,', $ids) . ",'");
                return ['code' => "SUCCESS", 'data' => $db->where('subscribe', '1')->limit(200)->column('nickname')];
            default :
                $news_id = $this->request->get('id', '');
                // 显示及图文
                $newsinfo = WechatService::getNewsById($news_id);
                // Get 请求，显示选择器界面
                if ($this->request->isGet()) {
                    $fans_tags = Db::name('WechatFansTags')->select();
                    array_unshift($fans_tags, [
                        'id'    => 0, 'name' => '全部',
                        'count' => Db::name('WechatFans')->where('subscribe', '1')->count(),
                    ]);
                    return $this->fetch('wechat/news/push',['vo' => $newsinfo, 'fans_tags' => $fans_tags,'iframe'=>$this->request->get('iframe')]);
                }
                // Post 请求，执行图文推送操作
                $post = $this->request->post();
                empty($post['fans_tags']) && $this->error('还没有选择要粉丝对象！');
                // 图文上传操作
                !$this->_uploadWechatNews($newsinfo) && $this->error('图文上传失败，请稍候再试！');
                // 数据拼装
                $data = [];
                if (in_array('0', $post['fans_tags'])) {
                    $data['msgtype'] = 'mpnews';
                    $data['filter'] = ['is_to_all' => true];
                    $data['mpnews'] = ['media_id' => $newsinfo['media_id']];
                } else {
                    $data['msgtype'] = 'mpnews';
                    $data['filter'] = ['is_to_all' => false, 'tag_id' => join(',', $post['fans_tags'])];
                    $data['mpnews'] = ['media_id' => $newsinfo['media_id']];
                }
                $wechat = load_wechat('Receive');
                if (false !== $wechat->sendGroupMassMessage($data)) {
                    LogService::write('微信管理', "图文[{$news_id}]推送成功");
                    $this->success('微信图文推送成功！', '');
                }
                $this->error("微信图文推送失败，{$wechat->errMsg} [{$wechat->errCode}]");
        }
    }


}